from flask import Flask, request, jsonify
import requests
import os

AnythingLL_Config = {"workspace_id": "your_workspace_id_here",
                     "api_key": "your_api_key_here",
                     "Anythingllm_Key": "Z27C9VS-AZZMGRE-KY8Z7T8-6XY3TQS",
                     "Anythingllm_Model": ""

                     }

app = Flask(__name__)

UPLOAD_FOLDER = 'uploaded_docs'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


@app.route('/process', methods=['POST'])
def process_data():
    # 获取文件和文本数据
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    if file:
        filename = os.path.join(UPLOAD_FOLDER, file.filename)
        file.save(filename)

    # 获取文本数据
    text_data = request.form.get('text', '')
    if not text_data:
        return jsonify({'error': 'No text data provided'}), 400

    # 调用AnythingLLM的API来处理文档和文本问题
    response = call_anything_llm_api(filename, text_data)
    return jsonify(response)


def call_anything_llm_api(document_path, query_text):
    workspace_id = 'your_workspace_id_here'
    api_key = 'your_api_key_here'

    # 上传文档到AnythingLLM
    upload_url = f'https://your-anythingllm-instance.com/api/workspaces/{workspace_id}/documents'
    with open(document_path, 'rb') as file:
        files = {'file': (os.path.basename(document_path), file, 'application/pdf')}  # 假设文件是PDF
        upload_response = requests.post(upload_url, headers={'Authorization': f'Bearer {api_key}'}, files=files)

    if upload_response.status_code != 200:
        return {'error': f'Failed to upload document: {upload_response.text}'}

    # 发送问题或查询，包括用户传入的文本
    query_url = 'https://your-anythingllm-instance.com/api/query'
    query_response = requests.post(query_url, headers={'Authorization': f'Bearer {api_key}'},
                                   json={'workspaceId': workspace_id, 'query': query_text})

    if query_response.status_code != 200:
        return {'error': f'Failed to query document: {query_response.text}'}

    return query_response.json()


if __name__ == '__main__':
    app.run(debug=True)
